const OAuth = require('wechat-oauth');
const cache = require('./cache');
const Promise = require('bluebird');

const appid = process.env.WECHAT_APPID;
const secret = process.env.WECHAT_SECRET;

const getToken = function(openid, callback) {
    return cache.get(openid)
    .then(token => {
        token = JSON.parse(token);
        callback(null, token);
    })
    .catch(err => {
        callback(err);
    });
};

const saveToken = function(openid, token, callback) {
    return cache.set(openid, token, 24 * 60)
    .then(token => {
        callback(null, token);
    })
    .catch(err => {
        callback(err);
    });
};

const oauth = new OAuth(appid, secret, getToken, saveToken);

module.exports = {
    client: oauth,
    utils: {
        getAccessToken: function(code) {
            return new Promise((resolve, reject) => {
                oauth.getAccessToken(code, function(err, result) {
                    if(err) {
                        reject(err);
                        return;
                    }
                    resolve(result);
                });
            });
        },
        getUser: function(openid) {
            return new Promise((resolve, reject) => {
                oauth.getUser(openid, function(err, result) {
                    if(err) {
                        reject(err);
                        return;
                    }
                    resolve(result);
                });
            });
        }
    }
};
